from django.shortcuts import render
from rest_framework.viewsets import ModelViewSet
from user_operation.models import *
from .serializers import *
from rest_framework.permissions import IsAuthenticated
from utils.permissions import IsOwnerOrReadOnly
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework.authentication import SessionAuthentication


# 用户收藏
class UserFavViewset(ModelViewSet):

    # 配置IsAuthenticated后，判断是否登陆？未登录，不能查看收藏信息
    # 配置IsOwnerOrReadOnly后, 验证当前删除收藏的用户，是不是request.user？
    permission_classes = (IsAuthenticated, IsOwnerOrReadOnly)
    # 不仅要登陆，还要把session,token或JWT返回给前端
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)

    # 默认是根据主键pk查询，设置为按商品id查询
    lookup_field = 'goods_id'

    # serializer_class = UserFavSerializer
    # 动态获取序列化对象:
    def get_serializer_class(self):
        if self.action == 'list':
            return UserFavDetailSerializer
        elif self.action == 'create':
            return UserFavSerializer
        return UserFavSerializer

    def get_queryset(self):
        return UserFav.objects.filter(user=self.request.user)


# 用户留言视图类
class LeavingMessageViewset(ModelViewSet):

    serializer_class = UserLeavingMessageSerializer
    # 不仅要登陆，还要把session,token或JWT返回给前端
    permission_classes = (IsAuthenticated, IsOwnerOrReadOnly)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)

    def get_queryset(self):
        return UserLeavingMessage.objects.filter(user=self.request.user)


# 地址视图类
class AddressViewset(ModelViewSet):

    serializer_class = UserAddressSerializer

    permission_classes = (IsAuthenticated, IsOwnerOrReadOnly)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)

    def get_queryset(self):
        return UserAddress.objects.filter(user=self.request.user)



